package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 权限的分页 , 模糊查询功能 -> permission.html
     * @author Qifei
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<Permission> list = permissionMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 权限新增 -> permission.html
     * @author Qifei
     * @param permission
     */
    @Override
    public void add(Permission permission) {
        permissionMapper.add(permission);
    }

    @Override
    public Permission findPermissionById(Integer id) {
        Permission permission = permissionMapper.findPermissionById(id);
        return permission;
    }

    /**
     * 权限的编辑 -> permission.html
     * @author Qifei
     * @param permission
     * @throws RuntimeException
     */
    @Override
    public void edit(Permission permission) throws RuntimeException {
        Integer count = permissionMapper.edit(permission);
        if (null == count ){
            throw new RuntimeException("编辑失败");
        }
    }

    /**
     * 权限的删除 -> permission.html
     * @author Qifei
     * @param id
     * @throws RuntimeException
     */
    @Override
    public void delete(Integer id) throws RuntimeException {
        Integer count = permissionMapper.findRoleAndPermissionById(id);
        if (count != null && count > 0){
            throw new RuntimeException("此条记录存在引用，不能删除");
        }else {
            permissionMapper.delete(id);
        }
    }

    /**
     * 查询所有的权限,让role.html点击编辑,在其标签页可以显示-> role.html
     * @author Qifei
     * @return
     */
    @Override
    public List<Permission> findAll() {
        List<Permission> permissionList = permissionMapper.findAll();
        return permissionList;
    }
}
